package com.hzcc.hzccblog.shiro;

import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * @Author 早睡蛋
 * @Date 2022/7/18 15:44:08
 * @Desc:重写shiro的session会话管理
 */

public class ShiroSessionManager extends DefaultWebSessionManager {

    private static final String AUTH_TOKEN = "access_token";

    public ShiroSessionManager(){
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String sessionId = WebUtils.toHttp(request).getParameter(AUTH_TOKEN);
        if (StringUtils.isEmpty(sessionId)){
            return super.getSessionId(request,response);
        }else {
            if (WebUtils.isTrue(request,"__cookie")){
                Cookie template = getSessionIdCookie();
                Cookie cookie = new SimpleCookie(template);
                cookie.setValue(sessionId);
                cookie.saveTo(WebUtils.toHttp(request),WebUtils.toHttp(response));
            }
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,ShiroHttpServletRequest.URL_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            return sessionId;
        }
    }
}
